﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

/// <summary>
/// DBClass 的摘要说明
/// </summary>
public class DBClass
{
    SqlConnection myConn;
    SqlCommand myCmd;
    DataSet ds;
    SqlDataAdapter adapt;
	public DBClass()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    public SqlConnection GetConnection()
    {
        string mystr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        myConn = new SqlConnection(mystr);
        return myConn;
    }
    public void ExecNonQuery(string strSql)
    {
        try
        {
            myConn = GetConnection();
            myCmd = new SqlCommand();
            myCmd.Connection = myConn;
            myCmd.CommandText = strSql;
            if (myCmd.Connection.State != ConnectionState.Open)
            {
                myCmd.Connection.Open();
            }
            myCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
        finally
        {
            if (myCmd.Connection.State == ConnectionState.Open)
            {
                myCmd.Connection.Close();
                myConn.Dispose();
                myCmd.Dispose();
            }
        }

    }
    public string ExecScalar(string strSql)
    {
        try
        {
            myConn = GetConnection();
            myCmd = new SqlCommand();
            myCmd.Connection = myConn;
            myCmd.CommandText = strSql;
            if (myCmd.Connection.State != ConnectionState.Open)
            {
                myCmd.Connection.Open();
            }
            strSql = Convert.ToString(myCmd.ExecuteScalar());
            return strSql;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
        finally
        {
            if (myCmd.Connection.State == ConnectionState.Open)
            {
                myCmd.Connection.Close();
                myConn.Dispose();
                myCmd.Dispose();
            }
        }
    }
    public DataTable GetDataSet(string strSql, string TableName)
    {
        ds = new DataSet();
        try
        {
            myConn = GetConnection();
            adapt = new SqlDataAdapter(strSql, myConn);
            adapt.Fill(ds, TableName);
            return ds.Tables[TableName];
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
        finally
        {
            myConn.Close();
            adapt.Dispose();
            ds.Dispose();
            myConn.Dispose();
        }
    }
}